package transporte.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import transporte.server.seguridad.NoPrivsException;

public class ExceptionResolver extends SimpleMappingExceptionResolver{

	private static final Log logger = LogFactory.getLog(ExceptionResolver.class);

	/**
	 * Extends the exception resolution to perform logging of the error
	 */
	public ModelAndView resolveException(HttpServletRequest req, HttpServletResponse res, Object handler, Exception ex)
	{
		if (ex instanceof NoPrivsException) {
			Map<String, Object> model = new HashMap<String, Object>();
			model.put("redirectUrl", req.getPathInfo());
			return new ModelAndView("/seguridad/login", model);
		}
		
		ModelAndView mv = super.resolveException(req, res, handler, ex);
		if (mv == null)
			return null;

		// When debug is enabled for the DispatcherServlet it prints the exception that called this resolver.   However,
		// in production we are not likely to have debug enabled and thus we would never see the exception unless
		// we print it here.  So, even though in development we are likely to see it twice, there is not an easy way around it.
		logger.error("Error: ", ex);
		
		return mv;
	}
	
}
